var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
const fs = require('file-stream-rotator');
const logger = require('morgan');

// 创建一个日志流，按日期滚动
const logStream = fs.getStream({
  date_format: 'YYYY-MM-DD',
  filename: path.join(__dirname, "logs") + '/access-%DATE%.log',
  frequency: 'daily',
  verbose: false
});

// var indexRouter = require("./routes/index");
// var articleRouter = require("./routes/article");
var agentsRouter = require("./routes/agents");
var ordersRouter = require("./routes/orders");
var salesRouter = require("./routes/sales");
var settleRouter = require("./routes/settle");
var usersRouter = require("./routes/users");

var mysql = require("./connect/index");
mysql.init();



var app = express();


app.set('port', 3000);

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(logger('combined', { stream: logStream })); // 日志


// 路由
// app.use("/", indexRouter);
// app.use("/article", articleRouter);
app.use("/api/agents", agentsRouter);
app.use("/api/orders", ordersRouter);
app.use("/api/sales", salesRouter);
app.use("/api/settle", settleRouter);
app.use("/api/users", usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});
app.listen(app.get('port'), () => {
  console.log(`Server running on port ${app.get('port')}`);
});

module.exports = app;
